import { showFailToast, showSuccessToast } from 'vant'
import { timeout, isString } from '@/utils'
import getFingerPrint from '@/utils/finger'

let clientId

const getClientId = async () => {
  if (clientId) return clientId
  clientId = await getFingerPrint()
  return clientId
}

const fetch = async (url, options) => {
  if (!isString(url)) {
    console.warn('url is must be string!')
    return
  }
  const $config = useRuntimeConfig()
  const reqUrl = url.indexOf('http') > -1 ? url : $config.app['BASE_URL'] + url

  if (!options.headers) {
    options.credentials = 'include' // 跨域携带cookie
    options.headers = {
      'X-XSRF-TOKEN': $config.app['XSRF_HEADER'],
      'APP-ID': $config.app['APP_ID'],
      'CLIENT-ID': await getClientId()
    }
  }

  return new Promise((resolve, reject) => {
    useFetch(reqUrl, { ...options }).then(({ data, error }) => {
      if (error && error.value) {
        showFailToast('网络错误')
        reject(error.value)
        return
      }
      const res = data.value
      if (res && res.code === 0) {
        res.notify && showSuccessToast(res.notify)
        // return res 正确应该返回
        resolve(data)
      } else if (res && (res.msg || res.errMsg || res.message)) {
        showFailToast(res.msg || res.errMsg || res.message)

        if (res.code === 403110) { // 会话过期跳登录
          timeout(1000).then(() => {
            navigateTo('/login')
          })
          return
        }
        reject(data)
      }
    }).catch(err => {
      reject(err)
    })
  })
}

export default new class Http {

  get(url, params) {
    return fetch(url, { method: 'GET', params })
  }

  post(url, body) {
    return fetch(url, { method: 'POST', body })
  }

  reqData(url, body) {
    return fetch(url, { method: 'POST', body, headers: {} })
  }
}
